import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
import { ElMessage } from 'element-plus'
import { staticRoutes, allAsyncRoutes, anyRoutes } from '@/router/routes'
import type { RouteRecordRaw } from 'vue-router';
import userInfoApi, { type userInfoModel } from '@/api/userInfo'
import { cloneDeep } from 'lodash'
import router from '@/router';

const resetUserInfo = (): userInfoModel => ({
  routes: [],
  buttons: [],
  roles: [],
  name: '',
  avatar: ''
})
// 过滤动态路由
const filterAsyncRoutes = (asyncRoutes: RouteRecordRaw[], menuRoutes: string[]) => {
  asyncRoutes = cloneDeep(asyncRoutes);
  let newAsyncRoutes = asyncRoutes.filter(route => {
    if (route.children?.length) {
      route.children = filterAsyncRoutes(route.children, menuRoutes)
    }
    return menuRoutes.includes(route.name as string)
  })
  return newAsyncRoutes
}
// 动态添加路由
const addRoutes = (asyncRoutes: RouteRecordRaw[]) => {
  let routes = asyncRoutes.concat(anyRoutes)
  routes.forEach(route => {
    router.addRoute(route);
  })
}

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {

  state: (): UserInfoState => ({
    token: getToken() as string,
    userInfo: resetUserInfo(),
    menuRoutes: []
  }),

  actions: {
    // 登录
    async login(username: string, password: string) {
      try {
        let result = await userInfoApi.login({ username, password })
        setToken(result.token)
        this.token = result.token
      } catch (error) {
        ElMessage.error('登录失败,请重试')
        return Promise.reject(error)
      }
    },
    // 获取用户信息
    async getInfo() {
      try {
        let result = await userInfoApi.info();
        // console.log(result);
        this.userInfo = result;
        const menuRoutes = result.routes;
        this.menuRoutes = staticRoutes.concat(filterAsyncRoutes(allAsyncRoutes, menuRoutes))
        addRoutes(this.menuRoutes);

      } catch (error) {
        ElMessage.error('获取用户信息失败,请重新登录')
        return Promise.reject(error)
      }
    },
    // 退出登录
    async reset() {
      try {
        await userInfoApi.logout();
        // 删除local中保存的token
        removeToken()
        // 重置用户信息
        this.userInfo = resetUserInfo()
        // 清除store中的token
        this.token = ''
      } catch (error) {
        ElMessage.error('退出登录失败,请重试')
        return Promise.reject(error)
      }
    },
  },
});
